<?php
/**
 * Created by PhpStorm.
 * User: wen
 * Date: 2021/7/4
 * Time: 15:46
 */

namespace WenRuns\Laravel;

use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Show;
use Illuminate\Support\Arr;

/**
 * Class Button
 * @method Button text($value = null)
 * @method Button class($value = null)
 * @method Button size($value = null)
 * @method Button type($value = null)
 * @method Button icon($value = null)
 * @method Button style($value = null)
 * @method Button attributes($value = null)
 * @method Button url($value = null)
 * @method Button id($value = null)
 * @method Button eventFn($value = null)
 * @package WenRuns\Services
 */
class Button
{
    /**
     * button text
     * @var
     */
    protected $text;

    /**
     * custom class name
     *
     * @var string
     */
    protected $class = '';

    /**
     * button size type
     *
     * @var string
     */
    protected $size = 'xs';

    /**
     * button type
     *
     * @var string
     */
    protected $type = 'default';

    /**
     * button icon
     *
     * @var string
     */
    protected $icon = '';

    /**
     * button's style
     *
     * @var string
     */
    protected $style = '';

    /**
     * button's attributes
     *
     * @var array
     */
    protected $attributes = [];

    /**
     * button's id attribute
     *
     * @var string
     */
    protected $id = '';

    /**
     * button jump link
     *
     * @var string
     */
    protected $url = 'javascript:void(0)';

    /**
     * whether the button is hidden
     *
     * @var bool
     */
    protected $hide = false;


    /**
     * button permission
     * @var null | string
     */
    protected $permission = null;

    /**
     * button click event
     *
     * @var null
     */
    protected $eventFn = null;

    /**
     * button size type options
     */
    const SIZE_SM = 'sm';
    const SIZE_XS = 'xs';

    /**
     * button type options
     */
    const TYPE_DEFAULT = 'default';
    const TYPE_WARNING = 'warning';
    const TYPE_DANGER = 'danger';
    const TYPE_SUCCESS = 'success';
    const TYPE_PRIMARY = 'primary';
    const TYPE_INFO = 'info';


    /**
     * Button constructor.
     * @param $text
     * @param array $options
     */
    public function __construct($text, $options = [])
    {
        $this->text = $text;
        foreach ($options as $key => $value) {
            $this->$key = $value;
        }
        $this->checkAssets();
    }

    public function checkAssets()
    {
        Laravel::loadJs('layui/layui.js');
        Laravel::loadCss('layui/css/layui.css');
        return $this;
    }

    /**
     * to set whether the button is hidden
     *
     * @param bool $value
     * @return $this
     */
    public function hide($value = true)
    {
        $this->hide = $value;
        return $this;
    }

    /**
     * to get the button url
     * @return Button
     */
    protected function getUrl()
    {
        if (empty($this->eventFn())) {
            return $this->url();
        }
        return 'javascript:void(0)';
    }

    /**
     * to get the button type
     *
     * @return Button
     */
    protected function getType()
    {
        return $this->type();
    }

    /**
     * to get button size type
     *
     * @return Button
     */
    protected function getSize()
    {
        return $this->size();
    }

    /**
     * to get the custom class
     *
     * @return Button
     */
    protected function getClass()
    {
        $class = $this->class();
        return is_array($class) ? implode(' ', $class) : $class;
    }

    /**
     * to get the button id attribute
     *
     * @return Button
     */
    protected function getId()
    {
        if (empty($this->id())) {
            $this->id('btn-' . md5($this->text() . mt_rand(0, 10000)) . '-' . time());
        }
        return $this->id();
    }

    /**
     * to get the button text
     *
     * @return Button
     */
    protected function getText()
    {
        return $this->text();
    }

    /**
     * to get the button style
     *
     * @return string|Button
     */
    protected function getStyle()
    {
        $style = $this->style();
        if (is_array($style)) {
            $str = '';
            foreach ($style as $name => $value) {
                $str .= $name . ':' . $value . ';';
            }
            return $str;
        }
        return $style;
    }

    /**
     * to get the button attributes
     *
     * @return string|Button
     */
    protected function getAttribute()
    {
        $attributes = $this->attributes();
        if (is_array($attributes)) {
            $str = '';
            foreach ($attributes as $key => $value) {
                $str .= $key . '="' . $value . '" ';
            }
            return $str;
        }
        return $attributes;
    }

    /**
     * to get the button icon
     *
     * @return string
     */
    protected function getIcon()
    {
        $icon = $this->icon();
        if (empty($icon)) {
            return '';
        }
        if (is_array($icon)) {
            $icon = implode(' ', $icon);
        }
        return '<i class="fa ' . $icon . '"></i>' . (empty($this->text()) ? '' : '&nbsp;&nbsp;');

    }

    /**
     * to set the button click event
     *
     * @return $this
     */
    protected function addScript()
    {
        $event = $this->eventFn();
        if ($event) {
            if (is_callable($event)) {
                $event = $event->call($this);
            }
            $pjax = self::pJax();
            $script = <<<SCRIPT
$(function(){
    $(".{$this->getId()}").click(function(e){
        e.preventDefault();
        var pJax = {$pjax};
        var fn = {$event};
        fn.call(this, e, pJax);
    });
});
SCRIPT;
            Admin::script($script);
        }
        return $this;
    }

    /**
     * the pJax request function
     *
     * @return string
     */
    public static function pJax()
    {
        $token = csrf_token();
        return <<<SCRIPT
function ({
    data = null,
    url = null,
    method = 'POST',
    dataType = 'json',
    callback = null,
    loadType = 2,
    success = null,
    fail = null,
}) {
    var loadingLayer = (loadType);
    if (data instanceof FormData) {
        data.append('_token', '{$token}');
    }else if(data instanceof Element){
        let inputs = data.querySelectorAll("[name]");
        if(["POST","PUT","PATCH","OPTIONS"].includes(method.toLocaleUpperCase())){
            let form = new FormData();
            form.append("_token", "{$token}");
            Array.from(inputs).forEach(el=>{
                form.append(el.name, el.value);
            });
            data = form;
        }else{
            let form = {
                _token:"{$token}",
            };
            Array.from(inputs).forEach(el=>{
                let arr = el.name.match(/([^\[\]]+)|\[([^\[\]]*)\]/img);
                if(arr.length){
                    let n = arr.pop().replace(/\[|\]/img, "");
                    if(arr.length){
                        let obj = form;
                        arr.forEach((v, i)=>{
                            let j = v.replace(/\[|\]/img, "");
                            if(j){
                                if(obj[j]){
                                    obj = obj[j];
                                }else{
                                    if(arr[i+1]){
                                        if(arr[i+1] == "[]"){
                                            obj[j] = new Array();
                                        }else{
                                            obj[j] = {};
                                        }
                                    }else if(n){
                                        obj[j] = {};
                                    }else{
                                        obj[j] = new Array();
                                    }
                                    obj = obj[j];
                                }
                            }else{
                                if(obj.length){
                                    for(let m in obj){
                                        if(arr[i+1]){
                                            if(obj[m][arr[i+1]] === undefined){
                                                obj = obj[m];
                                                break;
                                            }
                                        }else {
                                            if(obj[m][n] === undefined){
                                                obj = obj[m];
                                                break;
                                            }
                                        }
                                    }
                                    if(obj instanceof Array){
                                        obj.push({});
                                        obj = obj[obj.length-1];
                                    }
                                }else{
                                    obj.push({});
                                    obj = obj[0];
                                }
                            }
                        });
                        obj[n] = el.value;
                    }else{
                        form[n] = el.value;
                    }
                }else{
                    form[el.name] = el.value;
                }
            });
            data = form;
        }
    } else if(["POST","PUT","PATCH","OPTIONS"].includes(method.toLocaleUpperCase())){
        let form = new FormData();
        form.append('_token', "{$token}");
        if(data){
            const formatData = (obj, name="")=>{
                for(let i in obj){
                    let value = obj[i];
                    let _name = name ? name + '[' + i + ']' : i;
                    if(typeof value == "object" && !(value instanceof File)){
                        formatData(value,  _name);
                    }else{
                        form.append(_name, value);
                    }
                }
            }
            formatData(data);
        }
        data = form;
    }else{
        if(!data){
            data = {};
        }
        data._token = "{$token}";
    }
    $.ajax({
        url: url,
        data: data,
        method: method,
        dataType: dataType,
        contentType: false,
        processData: false,
        success: res => {
            callback && callback(res);
            success && success(res);
        },
        fail: err => {
            callback && callback(err);
            fail &&  fail(err);
        },
        complete: function(){
            layer.close(loadingLayer);
        },
    })
}
SCRIPT;

    }

    /**
     * output the button generates result
     *
     * @return string
     */
    public function render()
    {
        if ($this->hide || (!empty($this->permission) && !Admin::user()->can($this->permission))) {
            return '';
        }

        $this->addScript();
        return <<<HTML
<a href="{$this->getUrl()}"
   data-uri="{$this->url()}"
   class="btn btn-{$this->getType()} btn-{$this->getSize()} {$this->getClass()} {$this->getId()}"
   id="{$this->getId()}"
   title="{$this->getText()}"
   style="margin:2px;{$this->getStyle()}"
   {$this->getAttribute()}>
        {$this->getIcon()}{$this->getText()}
</a>
HTML;
    }

    /**
     *
     * @param $name
     * @param $arguments
     * @return $this|null
     */
    public function __call($name, $arguments)
    {
        if (empty($arguments)) {
            return $this->$name ?? null;
        }
        $this->$name = $arguments[0] ?? null;
        return $this;
    }

    /**
     * statically method to create the button
     *
     * @param array $options
     * @param bool $toString
     * @return array|string|static
     */
    public static function create(array $options, $toString = true)
    {
        $buttons = $toString ? '' : null;
        if (isset($options[0])) {
            foreach ($options as $k => $item) {
                $button = new static(Arr::get($item, 'text'), $item);
                if ($toString) {
                    $buttons .= $button->render();
                } else {
                    $buttons[] = $button;
                }
            }
        } else {
            $button = new static(Arr::get($options, 'text'), $options);
            if ($toString) {
                $buttons = $button->render();
            } else {
                $buttons = $button;
            }
        }
        return $buttons;
    }

    const SWAL_OPTIONS = [
        'type' => 'warning',
        'title' => '确认删除？',
        'confirmButtonText' => '确定',
        'showCancelButton' => true,
        'cancelButtonText' => '取消',
    ];

    /**
     * swal弹框， pjax执行
     * @param array|null $swalOptions
     * @param array $pJaxOptions
     * @param array $options
     * @return string
     */
    public static function eventSwal(array $swalOptions = null, array $pJaxOptions = [], $options = [])
    {
        //        $default = self::SWAL_OPTIONS;
//        $swalOptions = json_encode($default + $swalOptions, JSON_UNESCAPED_UNICODE);
        if (empty($swalOptions)) {
            $swalOptions = self::SWAL_OPTIONS;
        }
        $swalOptions = json_encode($swalOptions, JSON_UNESCAPED_UNICODE);
        $pJaxOptions = json_encode($pJaxOptions, JSON_UNESCAPED_UNICODE);
        $afterHook = $options['afterHook'] ?? 0;
        $beforeHook = $options['beforeHook'] ?? 0;
        $beforeHook = empty($beforeHook) ? 0 : $beforeHook;
        $script = $options['script'] ?? '';
        $loadType = $options['loading'] ?? 2;
        return <<<SCRIPT
function(e, pJax){
    const SWAL = function(){
        swal.fire({$swalOptions}).then(function(isConfirm){
            if(isConfirm.value){
                let options = {$pJaxOptions};
                if(options.url){
                    if(typeof options.callback == 'undefined'){
                        options.callback = function(res){
                            let afterHook = {$afterHook};
                            if(afterHook){
                                afterHook(res);
                            }else{
                                if(res.status){
                                    $.pjax.reload("#pjax-container");
                                    toastr.success(res.message);
                                }else{
                                    toastr.error(res.message);
                                }
                            }
                        }
                    }
                    let before = {$beforeHook};
                    if(before){
                        before.call(this, options);
                    }
                    if(options === false || options === "undefined"){
                        return false;
                    }
                    if(options.callback && typeof options.callback == 'string'){
                        eval('options.callback = ' + options.callback);
                    }
                    pJax(options);
                }
            }
        })
    };
    SWAL();
    {$script}
}
SCRIPT;
    }

    public static function eventLayer($options)
    {
        $options['title'] = $options['title'] ?? '弹窗';
        $options = self::checkLayerOptions($options);
        //        self::cssHandle();
        return <<<SCRIPT
function(e, pJax){
    let options ={
        type: {$options['type']},
        title: `{$options['title']}`,
        offset: `{$options['offset']}`,
        area: {$options['area']},
        shadeClose: {$options['shadeClose']}, //点击遮罩关闭
        content: `{$options['content']}`,
        anim: {$options['anim']}, //平滑放大。默认
        shade: {$options['shade']},
        maxmin: {$options['maxmin']},
        success: function(layer0, index){
            if({$options['iframeAuto']}){
                layer.iframeAuto(index)
            }
            let afterHook = {$options['afterHook']};
            if(afterHook){
                afterHook.call(this, {layer:layer0, index});
            }
        }
    }
    let beforeHook  = {$options['beforeHook']};
    if(beforeHook){
        beforeHook.call(this, options);
    }
    let index = layer["{$options['method']}"](options);
}
SCRIPT;
    }


    /**
     * html代码处理
     * @param $html
     * @return array|string|string[]|null
     */
    public static function htmlHandle($html)
    {
        return preg_replace(array("/\r\n|\r|\n/m", '/<\//m'), array(' ', '<\/'), $html);
    }

    /**
     * 自定义css加载
     */
    protected static function cssHandle()
    {
        $script = <<<SCRIPT
$(function(){
    let styleEle = document.createElement("style");
    styleEle.innerHTML = `
        @keyframes swal2loading{
            0%{
                transform: rotate(0deg);
            }
            100%{
                transform: rotate(-360deg);
            }
        }
        @-webkit-keyframes loading{
            0%{
                transform: rotate(0deg);
            }
            100%{
                transform: rotate(-360deg);
            }
        }
        .select2-container.select2-container--default.select2-container--open{
            z-index: 999999999999;
        }
        .layui-layer-content .iframe-loading svg{
            animation: swal2loading 1.2s infinite ease-in-out;
            -webkit-animation: swal2loading 1.2s infinite ease-in-out;
        }

        .layui-layer-content .icheck{
            margin: 0px 20px;
        }
    `;
    document.querySelector('head').append(styleEle);
});
SCRIPT;
        Admin::script($script);
    }

    /**
     * 弹出form表单
     * @param Form $form
     * @param string $script
     * @param string $width
     * @param string $height
     * @return string
     */
    public static function eventForm(Form $form, $options = [])
    {
        $options['title'] = $options['title'] ?? $form->builder()->title();
        $options = self::checkLayerOptions($options);

        $form->tools(function (Form\Tools $tools) {
            $tools->disableList();
            $tools->disableDelete();
            $tools->disableView();
        });
        $form->footer(function (Form\Footer $footer) {
            $footer->disableEditingCheck();
            $footer->disableViewCheck();
            $footer->disableCreatingCheck();
        });
        self::cssHandle();
        $fields = $form->builder()->fields();
        $formHtml = self::htmlHandle($form->render());
        $fields->each(function ($field) use (&$options) {
            $field->render();
            $options['script'] .= $field->getScript() . ' ';
        });
        //        $area = is_array($options['area']) ? json_encode($options['area']) : '"' . $options['area'] . '"';
//        $afterSubmit = empty($options['afterSubmit']) ? 0 : $options['afterSubmit'];
//        $beforeSubmit = empty($options['beforeSubmit']) ? 0 : $options['beforeSubmit'];
//        $loadType = $options['loading'] ?? 2;
        return <<<SCRIPT
function(e, pJax){
    layer.open({
        type: 1,
        title: `{$options['title']}`,
        offset: `{$options['offset']}`,
        area: {$options['area']},
        shadeClose: {$options['shadeClose']}, //点击遮罩关闭
        content: `{$formHtml}`,
        anim: {$options['anim']}, //平滑放大。默认
        shade: {$options['shade']},
        maxmin: {$options['maxmin']},
        success: (layer0, index)=>{
            $('.layui-layer-content form button[type="submit"]').click((event)=>{
                var e = event || window.event;
                let form = e.currentTarget.parentElement;
                while(form.tagName != 'FORM'){
                    form = form.parentElement;
                }
                let requiredEles = form.querySelectorAll("[name][required]");
                if(Array.from(requiredEles).filter((ele)=>{
                    return !ele.value && ele.value!==0;
                }).length){
                    return ;
                }
                e.preventDefault();
                if(e.currentTarget.dataset.submiting=="true"){
                    toastr.info("正在马不停蹄的提交中...");
                    return ;
                }
                e.currentTarget.dataset.submiting="true";
                let btnText = e.currentTarget.innerHTML;
                e.currentTarget.innerHTML = `<i class="fa fa-asterisk icon-loading"><\/i>&nbsp;&nbsp;`+btnText;
                const submitForm = (resolve, reject) => {
                    try{
                        let before = {$options['beforeSubmit']};
                        if(before){
                            before.call(this, form, e);
                        }
                        let formData = new FormData(form);
                        pJax({
                            url: form.getAttribute("action"),
                            data: formData,
                            method: form.getAttribute("method"),
                            callback: function(res){
                                let after = {$options['afterSubmit']};
                                if(after){
                                    let rsp = after.call(this, {data:res, form});
                                    if(rsp instanceof Promise){
                                        rsp.then((r)=>{
                                            resolve(r);
                                        }).catch((e)=>{
                                            reject(e);
                                        })
                                    }else{
                                        e.currentTarget.dataset.submiting="false";
                                        e.currentTarget.innerHTML = btnText;
                                    }
                                    return ;
                                }
                                if(res.status){
                                    resolve(res);
                                }else{
                                    reject(res);
                                }
                            },
                        });
                    }catch(err){
                        reject(err);
                    }
                }
                new Promise((resolve, reject)=>{
                    let submitEvent = {$options['submitEvent']};
                    if(submitEvent){
                        submitEvent.call(this, {e, pJax, submit, resolve, reject});
                    }else{
                        submitForm(resolve, reject);
                    }
                }).then((res)=>{
                    layer.close(index);
                    $.pjax.reload("#pjax-container");
                    toastr.success(res.message || res.msg || res);
                }).catch((err)=>{
                    toastr.error(err.message || err.msg || err);
                }).finally(()=>{
                    e.currentTarget.dataset.submiting="false";
                    e.currentTarget.innerHTML = btnText;
                });

            });
            {$options['script']}
        },
    });
}
SCRIPT;
    }


    /**
     * 弹出show表单
     * @param Show $show
     * @param string $script
     * @param string $width
     * @param string $height
     * @return string
     */
    public static function eventShow(Show $show, $options = [])
    {
        $options['title'] = $options['title'] ?? '详情';
        $options = self::checkLayerOptions($options);
        $show->panel()->tools(function (Show\Tools $tools) {
            $tools->disableDelete();
            $tools->disableList();
            $tools->disableEdit();
        });
        $html = self::htmlHandle($show->render());
        //        $area = is_array($options['area']) ? json_encode($options['area']) : '"' . $options['area'] . '"';
        return <<<SCRIPT
function(e, pJax){
    layer.open({
        type: 1,
        title: `{$options['title']}`,
        offset: `{$options['offset']}`,
        area: {$options['area']},
        shadeClose: {$options['shadeClose']}, //点击遮罩关闭
        content: `{$html}`,
        anim: {$options['anim']}, //平滑放大。默认
        shade: {$options['shade']},
        maxmin: {$options['maxmin']},
        success: function(layer0, index){
            {$options['script']}
        }
    });
}
SCRIPT;
    }

    protected static function checkLayerOptions(array $options)
    {
        $area = $options['area'] ?? ['95%', '95%'];
        return [
            'method' => $options['method'] ?? 'open',
            'type' => $options['type'] ?? 1,
            'content' => $options['content'] ?? '',
            'submitEvent' => $options['submit'] ?? 'null', // 提交按钮点击事件
            'script' => $options['script'] ?? '', // 加载完成执行脚本
            'area' => is_array($area) ? json_encode($area) : '"' . $area . '"', // 宽高
            'offset' => $options['offset'] ?? '2%', // 距离
            'anim' => $options['anim'] ?? 2, // 动画效果
            'title' => $options['title'] ?? '', // 窗口标题
            'shadeClose' => $options['shadeClose'] ?? 'false', // 点击背景关闭
            'shade' => $options['shade'] ?? 0.3, // 背景透明度
            'maxmin' => $options['maxmin'] ?? 'false', //开启最大化最小化按钮
            'iframeAuto' => $options['iframeAuto'] ?? 'false', // 窗口高度自适应
            'beforeSubmit' => $options['beforeSubmit'] ?? 'null', // 提交之前
            'afterSubmit' => $options['afterSubmit'] ?? 'null', // 提交之后
            'beforeHook' => $options['beforeHook'] ?? 'null', // 前钩子
            'afterHook' => $options['afterHook'] ?? 'null',// 后钩子
            'timeout' => $options['timeout'] ?? 0,// 超时时间，单位：秒
        ];
    }


    /**
     * iframe方式加载页面
     * @param $url
     * @param string $submitEvent
     * @param string $width
     * @param string $height
     * @return string
     */
    public static function eventIframe($url, $options = [])
    {
        $options['title'] = $options['title'] ?? $url;
        $options = self::checkLayerOptions($options);
        self::cssHandle();
        return <<<SCRIPT
function(e, pJax){
    let options ={
        type: 2,
        title: `{$options['title']}`,
        offset: `{$options['offset']}`,
        area: {$options['area']},
        shadeClose: {$options['shadeClose']}, //点击遮罩关闭
        content: `{$url}`,
        anim: {$options['anim']}, //平滑放大。默认
        shade: {$options['shade']},
        maxmin: {$options['maxmin']},
        success: function(layer0, index){
            if({$options['iframeAuto']}){
                layer.iframeAuto(index)
            }
            let ele = layer0[0];
            let iframe = ele.querySelector('iframe');
            let iframeDocument = iframe.contentDocument || window.frames[iframe.name].document || ele;
            let afterHook = {$options['afterHook']};
            if(afterHook){
                afterHook.call(this, {layer:layer0, document: iframeDocument, iframe});
            }
            $(iframeDocument).on('click','form button[type="submit"]',function(event){
                var e = event || window.event;
                let form = e.currentTarget.parentElement;
                while(form.tagName != 'FORM'){
                    form = form.parentElement;
                }
                let requiredEles = form.querySelectorAll("[name][required]");
                if(Array.from(requiredEles).filter((ele)=>{
                    return !ele.value && ele.value !== 0;
                }).length){
                    return ;
                }
                e.preventDefault();
                if(e.currentTarget.dataset.submiting=="true"){
                    toastr.info("正在马不停蹄的提交中...");
                    return ;
                }
                e.currentTarget.dataset.submiting="true";
                let btnText = e.currentTarget.innerHTML;
                e.currentTarget.innerHTML = `<i class="fa fa-asterisk icon-loading"><\/i>&nbsp;&nbsp;`+btnText;
                var submitForm = function(resolve, reject){
                    try{
                        let submit_status = true;
                        if({$options['timeout']} > 0){
                            let h = setTimeout(()=>{
                                clearTimeout(h);
                                if(submit_status){
                                    reject({message:'提交超时未处理！'});
                                }
                            }, {$options['timeout']}*1000);
                        }
                        let beforeSubmit = {$options['beforeSubmit']};
                        if(beforeSubmit){
                            beforeSubmit.call(this, form, e);
                        }
                        let formData = new FormData(form);
                        pJax({
                            url: form.getAttribute("action"),
                            data: formData,
                            method: form.getAttribute("method"),
                            callback: function(res){
                                try{
                                    submit_status = false;
                                    let afterSubmit = {$options['afterSubmit']};
                                    if(afterSubmit){
                                        let rsp = afterSubmit.call(this, {data:res, form});
                                        if(rsp instanceof Promise){
                                            rsp.then((r)=>{
                                                resolve(r);
                                            }).catch((e)=>{
                                                reject(e);
                                            });
                                        }else{
                                            e.currentTarget.dataset.submiting="false";
                                            e.currentTarget.innerHTML = btnText;
                                        }
                                        return;
                                    }
                                    if(res.status){
                                        resolve(res);
                                    }else{
                                        reject(res);
                                    }
                                }catch(err){
                                    reject(res.responseJSON || err);
                                }
                            },
                        });
                    }catch(err){
                        reject(err.message||err);
                    }
                }
                new Promise((resolve, reject)=>{
                    let submitEvent = {$options['submitEvent']};
                    if(submitEvent){
                        submitEvent.call(this, {e, pJax, submit, resolve, reject});
                    }else{
                        submitForm(resolve, reject);
                    }
                }).then((res)=>{
                    layer.close(index);
                    $.pjax.reload("#pjax-container");
                    toastr.success(res.message || res.msg || res);
                }).catch((err)=>{
                    toastr.error(err.message || err.msg || err);
                }).finally(()=>{
                    e.currentTarget.dataset.submiting="false";
                    e.currentTarget.innerHTML = btnText;
                });
            });
        }
    }
    let beforeHook  = {$options['beforeHook']};
    if(beforeHook){
        beforeHook.call(this, options);
    }
    let index = layer.open(options);
}
SCRIPT;
    }


}
